package rwlivbk.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import rwlivbk.common.CommonResult;
import rwlivbk.mapper.EventMapper;
import rwlivbk.model.Event;
import rwlivbk.model.SignUpRequest;
import rwlivbk.utils.JwtTokenUtil;

import java.util.ArrayList;

@RestController
@CrossOrigin
@RequestMapping("/admin-api/events")
public class EventController {

    private final EventMapper eventMapper;
    private final JwtTokenUtil jwtTokenUtil;

    @Autowired
    public EventController(EventMapper eventMapper, JwtTokenUtil jwtTokenUtil) {
        this.eventMapper = eventMapper;
        this.jwtTokenUtil = jwtTokenUtil;
    }

    @GetMapping("/getAllEvents")
    public CommonResult<?> getAllEvents() {
        ArrayList<Event> events = eventMapper.findAllEvents();
        return CommonResult.success(events);
    }

    @GetMapping("/getCurrentEvents")
    public CommonResult<?> getCurrentEvents() {
        ArrayList<Event> events = eventMapper.findAllCurrentEvents();
        return CommonResult.success(events);
    }

    @GetMapping("/getHistoryEvents")
    public CommonResult<?> getHistoryEvents() {
        ArrayList<Event> events = eventMapper.findHistoryEvents();
        return CommonResult.success(events);
    }

    @PostMapping("/add")
    public CommonResult<?> addNewEvent(@RequestBody Event eventData) {
        eventMapper.addEvent(eventData);
        return CommonResult.success(200);
    }

    @PutMapping("/update")
    public CommonResult<?> updateEvent(@RequestBody Event updatedData) {
        eventMapper.updateEvent(updatedData);
        return CommonResult.success(200);
    }

    @PostMapping("/signUp")
    public CommonResult<?> signUpForEvent(@RequestHeader("Authorization") String authHeader, @RequestBody SignUpRequest request) {
        int eventId = request.getId();
        try {
            String token = authHeader.substring(7); // 去除 "Bearer " 前缀
            if (!jwtTokenUtil.validateToken(token)) {
                return CommonResult.error(50008, "无效的访问令牌");
            }

            String username = jwtTokenUtil.getUsernameFromToken(token);
            eventMapper.signUpForEvent(username, eventId);
            return CommonResult.success(200);
        } catch (Exception e) {
            return CommonResult.error(50006, "报名失败");
        }
    }

    @GetMapping("/getSignUpsByEventId/{event_id}")
    public CommonResult<?> getSignUpsByEventId(@PathVariable int event_id) {
        ArrayList<SignUpRequest> signUps = eventMapper.findSignUpsByEventId(event_id);
        System.out.println("Returning sign-ups: " + signUps);

        return CommonResult.success(signUps);
    }
}
